package com.hfi.security.core.authentication.mobile;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author ChangLiang
 * @date 2019/8/14
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    /**
     * 进行身份认证的逻辑写在这里
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken smsCodeAuthenticationToken = (SmsCodeAuthenticationToken) authentication;
        // 根据手机号作为username来读取用户信息
        // this is a trick 因为我们并没有使用真正的数据库 应该是根据mobile来读取用户信息的
        UserDetails userDetails =
                userDetailsService.loadUserByUsername(smsCodeAuthenticationToken.getPrincipal().toString());
        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        SmsCodeAuthenticationToken result = new SmsCodeAuthenticationToken(userDetails, userDetails.getAuthorities());
        // new好了已经认证的信息之后 要把userDetails copy一下
        // 把未认证的TOKEN中的details copy到 已认证的TOKEN中 为啥要有这样的过程 因为detail中封装的是请求的一些信息 比如ip之类的
        result.setDetails(smsCodeAuthenticationToken.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // SmsCodeAuthenticationToken是传入的authentication的 parent 或 同级
        boolean b = SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
        return b;
    }
}
